package com.whitedust.top60;

import com.whitedust.structure.TreeNode;

import java.util.Set;

/**
 *
 * @author A
 * @since 2025/11/11 12:54
 */

public class Top57 {
    public TreeNode buildTree(int[] preorder, int[] inorder) {

        return build(preorder, inorder, 0, preorder.length, 0, inorder.length);
    }

    private TreeNode build(int[] pre, int[] in, int pStart, int pEnd, int iStart, int iEnd) {
        if (pStart == pEnd) return null;
        TreeNode root = new TreeNode(pre[pStart]);
        int rootIndex = 0;
        for (int i = iStart; i < iEnd; i++) {
            if (in[i] == root.val) {
                rootIndex = i;
                break;
            }
        }
        int leftNum = rootIndex - iStart;
        root.left = build(pre, in, pStart + 1, pStart + leftNum + 1, iStart, rootIndex);
        root.right = build(pre, in, pStart + leftNum + 1, pEnd, rootIndex + 1, iEnd);
        return root;
    }
}
